package com.westcom.vulb.activity;

import java.text.DecimalFormat;

import com.westcom.vulb.bean.Session;
import com.westcom.vulb.common.MulitPointTouchListener;
import com.westcom.vulb.logic.SessionManager;
import com.westcom.vulb.logic.account;
import com.westcom.vulb.protocal.http.Response;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.*;

public class CardImageDetailActivity extends BasicActivity
{
	ImageView iv_img,iv_save,iv_dele;
	TextView tv_fileType,tv_fileSize,tv_pop_save;
	private int resId = 0;
	private Bitmap mImg = null;
	private String mFileName = "";
	private int mFileSize = 0;
	private String mFileType = "";
	private static final int GET_IMG = 0x01;
	private boolean isDele = false;
	private PopupWindow mPopWindowSave = null;
	LinearLayout ll_tab_bar = null;	
	
    private OnClickListener l = new OnClickListener()
    {
		@Override
		public void onClick(View v) 
		{
			switch(v.getId())
			{
				case R.id.iv_card_img_save:
				{
					if(mPopWindowSave.isShowing())
					{
						mPopWindowSave.dismiss();
					}else
					{
						//mPopWindowSave.showAsDropDown(v);
						mPopWindowSave.showAsDropDown(v,0,-(ll_tab_bar.getHeight()*2));
					}
				}break;
				case R.id.iv_card_img_dele:
				{
					if(!mFileName.isEmpty())
					{
						showdeleConfrimdialog(mFileName);
					}
				}break;
				case R.id.tv_card_image_detail_pop_save:
				{
					if(mPopWindowSave.isShowing())
					{
						mPopWindowSave.dismiss();
					}
				}break;
				default:{}break;
			}
		}
    };
    
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		switch(keyCode)
		{
			case KeyEvent.KEYCODE_BACK:
			{
				Intent intent = new Intent();
				intent.putExtra("delete", isDele);
				intent.putExtra("resId", resId);
				setResult(RESULT_OK,intent);
		        finish();
			}break;
		}
		return false;	
	}
    
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) 
        {
            switch(msg.what)
            {
	            case GET_IMG:
	            {
	            	if(mLoadingDialog.isShowing())
	            	{
	            		mLoadingDialog.hide();
	            	}
	            	if (msg.arg1 == Response.SUCCESS) 
	                {
	        			Session.getResourceResponse res = (Session.getResourceResponse)msg.obj;//success
	        			String json_str = Session.readString(res.filePath);
	        			Response response = Response.parse(json_str);
	        			mFileName = (String)response.data.get("fileName");
	        			mFileSize = (Integer)response.data.get("fileSize");
	        			mFileType = (String)response.data.get("mimeType");
	        			mImg = account.Base64Str2Bitmap((String)response.data.get("resourceData"));
	        			iv_img.setImageBitmap(mImg);
	                }else
	                {
	                	launchToast(getResources().getString(R.string.download_error) + ":"+msg.arg1);
	                }
	            	setFileSize();
	            	setFileType();
	            }break;
	            default:{}break;
            }
            return false;
        }
    });
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_image_detail);
        tv_fileType = (TextView)findViewById(R.id.tv_card_img_img_type);
        tv_fileSize = (TextView)findViewById(R.id.tv_card_img_img_size);
        iv_img = (ImageView)findViewById(R.id.iv_card_img_img);
        iv_save = (ImageView)findViewById(R.id.iv_card_img_save);
        iv_dele = (ImageView)findViewById(R.id.iv_card_img_dele);
        iv_save.setOnClickListener(l);
        iv_dele.setOnClickListener(l);
        iv_img.setOnTouchListener(new MulitPointTouchListener());
        resId = this.getIntent().getIntExtra("resId",0);
        if(resId >0)
        {
        	SessionManager.getInstance().getCurrentSession().getResource(resId,1,mHandler.obtainMessage(GET_IMG));
            mLoadingDialog.setMessage(getResources().getString(R.string.loading));
            mLoadingDialog.show();
        }
        View savePopView = View.inflate(this, R.layout.popwindow_card_image_detail_save, null);
        tv_pop_save = (TextView)savePopView.findViewById(R.id.tv_card_image_detail_pop_save);
        tv_pop_save.setOnClickListener(l);
        mPopWindowSave = new PopupWindow(savePopView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        ll_tab_bar = (LinearLayout)findViewById(R.id.ll_card_image_detail_tabBar);
    }
    private void setFileSize()
    {
    	String size = "";
    	DecimalFormat a = new DecimalFormat(".0");
    	if(mFileSize > 1024*1024)
    	{
    		double value = (double)mFileSize/(double)1024*1024;
    		size = ""+a.format(value)+"MB";
    	}else
    	{
    		double value = (double)mFileSize/(double)1024;
    		size = ""+a.format(value)+"KB";
    	}
    	tv_fileSize.setText(size);
    }
    private void setFileType()
    {
    	tv_fileType.setText(mFileType);
    }
    
    protected void showdeleConfrimdialog(String title) 
	{
		AlertDialog.Builder builder = new Builder(this);
		builder.setTitle(title);
		builder.setMessage(R.string.del_confirm);
		builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				// TODO Auto-generated method stub
				iv_img.setImageResource(R.drawable.icon_tool_picture_gray_disable);
				isDele = true;
				dialog.dismiss();
			}});
		
		builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				// TODO Auto-generated method stub
				isDele = false;
				dialog.dismiss();
			}});
		builder.create().show();
	}
}
